import styles from "./home.module.scss"
import { Row, Col, Drawer, Card, Avatar, Carousel, Input, Image, message } from "antd"
import { SmileOutlined, BilibiliFilled, UserOutlined } from "@ant-design/icons"
import React, { useEffect, useState } from "react"
import { useSelector } from 'react-redux'
import FoodItem from "@/components/FoodItem"
import { animated, useSpring } from '@react-spring/web'
import { Getlist, GetComment, searchfood, GetSwiper } from "@/apis/foods"
import { useNavigate } from "react-router-dom"
const base_url = import.meta.env.VITE_APP_URL
type Item = {
    Cover_img: string,
    review: number,
    texttual: string
    title: string
    _id: string
}

let timer1: any = null
const Home = () => {

    const navigate = useNavigate()
    const userinfo = useSelector((state: any) => state.UserStore.userinfo)
    const usercollect = useSelector((state: any) => state.UserStore.usercollect)
    const springs = useSpring({
        from: { opacity: 0 },
        to: { opacity: 1 },
        config: { duration: 1000 }
    })
    const thems = useSelector((state: any) => state.Appstore.theme)
    const [mobile_show, set_show] = useState(false)
    const [useinfo_show, setuser_info] = useState(false)
    const [loading, setLoading] = React.useState<boolean>(true);
    const [CurrentPage, setCurrenPage] = useState(1)
    const [FoodList, setFoodelist] = useState<any>([])
    const [isButton, setIsbutton] = useState(false)
    const [recomment, setcomment] = useState<any>([])
    const [swiper, setswipet] = useState<any>([])


    //搜索1
    const [search1, setsearch1] = useState("")
    const [searchList, setsearchList1] = useState<any>([])
    //回车
    const onPressEnter = (e: any) => {
        if (e.target.value || searchList.length !== 0) {
            console.log(searchList)
            searchList[0]._id && navigate(`/detaile/${searchList[0]._id}`)
        }
    }
    const onChange1 = async (e: any) => {
        clearTimeout(timer1)
        if (e.target.value == "") {
            setsearchList1([])
            setsearch1(e.target.value)
            return
        }
        setsearch1(e.target.value)
        timer1 = setTimeout(async () => {
            const result = await searchfood(e.target.value)
            setsearchList1(result.data)
            console.log(result)
        }, 200);


    }
    const onfocus = async (e: any) => {
        if (e.target.value) {
            const result = await searchfood(e.target.value)
            setsearchList1(result.data)
        }

    }
    //搜索1
    const GetFoodList = async (current: number) => {
        const res = await Getlist(current * 9 - 9)
        console.log(res.data, '????/')
        if (res.data.length === 0) {
            message.info("没有更多了")
            setIsbutton(true)
            return
        }
        setFoodelist([...FoodList, ...res.data])
    }
    const SwiperList = async () => {
        const res = await GetSwiper()
        console.log(res, '2123132')
        setswipet([...res.data])
    }
    useEffect(() => {
        GetFoodList(CurrentPage)
    }, [CurrentPage])
    useEffect(() => {
        GetComm()
        SwiperList()
    }, [])
    const GetComm = async () => {
        const res = await GetComment()
        setcomment(res.data)
    }
    const showLoading = () => {
        set_show(true);
        setLoading(true);
        if (recomment.length != 0) {
            setLoading(false);

        }

    };
    const showUsesrloading = () => {
        setuser_info(true);
        setLoading(true);
        setTimeout(() => {
            setLoading(false);
        }, 0);
    }

    const secs = 'https://img.zcool.cn/community/01a6035bd11224a8012099c84fce6a.jpg@3000w_1l_0o_100sh.jpg'
    const emptylist = [
        {
            id: "1"
        },
        {
            id: "2"
        },

    ]

    const scrolls = (total: number, top: number, height: number) => {

        if (isButton) {
            return
        }
        if (total < top + height + 1) {
            console.log("到底了")
            console.log(window.innerHeight)
            setCurrenPage(CurrentPage + 1)
        }
    }
    return (
        <animated.div onScroll={(e: any) => scrolls(e.target.scrollHeight, e.target.scrollTop, e.target.clientHeight)} style={{ height: '92vh', overflow: "scroll" }}>
            <div className={styles.home} style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center" }}>
                <Row justify={"center"} style={{ margin: "10px 0", width: "100%" }}>
                    <Col xs={0} sm={8} md={8} lg={8}>
                        <div
                            style={{ width: "100%" }}
                        >
                            <div style={{ width: "100%", position: "relative", }}>
                                <Input
                                    onBlur={() => {
                                        setTimeout(() => {
                                            setsearchList1([])
                                        }, 100);
                                    }} onFocus={onfocus}
                                    value={search1} onPressEnter={onPressEnter} onChange={onChange1} style={{ width: "100%" }} />
                                {
                                    searchList.length !== 0 ? <div style={{ width: "100%", background: thems ? 'rgba(255,255,255,0.8)' : 'rgba(0,0,0,0.6)', position: "absolute", zIndex: 10, maxHeight: '150px', overflowY: "scroll" }}>

                                        {
                                            searchList.map(((item: any) => {

                                                return <p onClick={() => {
                                                    navigate(`/detaile/${item._id}`)
                                                }} className={thems ? styles.idhover : styles.idhover2} style={{ textAlign: "center", padding: "5px 0", }} key={item._id}>{item.title}</p>
                                            }))
                                        }
                                    </div> : ''
                                }

                            </div>
                        </div>


                    </Col>
                </Row>
                <div style={{ width: "65%", position: "relative", background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.4)', }}>
                    <Row justify={"center"}>
                        <Col xs={0} sm={24} md={24} lg={24}  >
                            <div style={{ width: "100%" }}>

                                <Carousel arrows autoplay fade={true} style={{ height: '350px' }}>

                                    {
                                        swiper.length && swiper.map((item: any, index: number) => {


                                            return <div onClick={() => {
                                                navigate(`/detaile/${item._id}`)
                                            }} key={index} style={{ width: "100%", height: "100%" }}>
                                                <Image preview={{
                                                    visible: false,
                                                    mask: ""

                                                }} src={base_url + item.Cover_img} width={'100%'} height={"350px"} >1</Image>
                                            </div>
                                        })
                                    }

                                </Carousel>
                            </div>
                        </Col>
                    </Row>
                    <Row justify={"space-evenly"} >
                        {
                            FoodList.length != 0 ? FoodList.map((item: any, index: number) => {
                                return <FoodItem key={index} keyIndex={index} item={item}></FoodItem>
                            }) : ''
                        }

                        {
                            emptylist.map((_, index) => {

                                return (
                                    <Col key={index} style={{ margin: "5px", }} xs={22} sm={20} md={11} lg={7} ></Col>
                                )
                            })
                        }
                    </Row>
                    <Row style={{ position: 'absolute', transform: 'translateX(103%)', right: 0, top: 0, width: '25%' }}>
                        <Col style={{ padding: "5px", background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.8)', }} xs={0} sm={0} md={24} lg={24}>
                            <div style={{ width: '100%', display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
                                <p style={{ fontSize: '20px', textAlign: "center", margin: '5px 0' }}>推荐</p>

                                {
                                    recomment.length != 0 ?

                                        recomment.map((item: Item, index: number) => {
                                            return <Card onClick={() => {
                                                navigate(`/detaile/${item._id}`)
                                            }} key={index} hoverable style={{ width: "100%", margin: "5px 0" }}
                                                cover={<img alt="example" style={{ width: "100%", height: '150px' }} src={base_url + item.Cover_img} />}
                                            >
                                                <div style={{}}>
                                                    <p className={styles.overline_1}><span>{item.title}</span> <span>{item.review}看</span></p>
                                                    <p className={styles.overline}>{item.texttual}</p>
                                                </div>
                                            </Card>
                                        })
                                        : ''
                                }


                            </div>
                        </Col>
                        <Col xs={20} sm={20} md={0} lg={0}>
                            <div style={{ padding: "5px", display: 'flex', flexDirection: "column", justifyContent: "center", alignItems: "center", background: thems ? "rgba(255,255,255,0.8)" : 'rgba(0,0,0,0.8)' }}>
                                <SmileOutlined onClick={showLoading} spin={true} style={{ fontSize: '30px' }} />
                                <p style={{ fontSize: '16px', fontFamily: "幼圆" }}>推荐</p>

                            </div>

                        </Col>

                    </Row>
                    <Row justify={"end"} style={{ position: 'absolute', transform: 'translateX(-103%)', left: 0, top: 0, width: '25%' }}>
                        <Col style={{ padding: "5px", background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.8)', }} xs={0} sm={0} md={24} lg={24}>
                            <div style={{ width: '100%', display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
                                <p style={{ fontSize: '20px', textAlign: "center", margin: '5px 0' }}>用户</p>
                                <Avatar className="editUser" alt="加载错误" size={
                                    {
                                        xs: 0,
                                        sm: 0,
                                        md: 90,
                                        lg: 100,
                                        xl: 100,
                                        xxl: 100
                                    }
                                } src={base_url + userinfo.avatar} style={{ margin: '5px 0' }}></Avatar>
                                <h1>{
                                    userinfo.username ? userinfo.username : ""
                                }</h1>
                                <p style={{ margin: "15px", lineHeight: "30px", fontFamily: "幼圆", }} className={styles.overline_1}><span>收藏：{usercollect.collect}</span> <span>发布：{usercollect.foods}</span> </p>
                                <a href={userinfo.bilibili ? userinfo.bilibili : ''} target="_blank" style={{ display: 'flex', flexDirection: "column", justifyContent: "center", alignItems: "center" }}><BilibiliFilled style={{ fontSize: 30, color: "deeppink" }} /> <span>bilibili</span></a>
                            </div>
                        </Col>
                        <Col xs={20} sm={20} md={0} lg={0}>
                            <div style={{ padding: "5px", display: 'flex', flexDirection: "column", justifyContent: "center", alignItems: "center", background: thems ? "rgba(255,255,255,0.8)" : 'rgba(0,0,0,0.8)' }}>
                                <UserOutlined onClick={showUsesrloading} style={{ fontSize: '30px' }} />
                                <p style={{ fontSize: '16px', fontFamily: "幼圆" }}>个人</p>

                            </div>

                        </Col>
                    </Row>
                </div>
                {/* 移动端推荐的抽屉 */}
                <Drawer
                    closable
                    destroyOnClose
                    rootClassName={styles.draw_right}
                    title={<p >推荐</p>}
                    placement="right"
                    open={mobile_show}
                    loading={loading}
                    onClose={() => set_show(false)}
                    style={{ width: '200px' }}
                    className={styles.draw_right}
                >

                    {
                        recomment.length != 0 ?

                            recomment.map((item: Item, index: number) => {
                                return <Card onClick={() => {
                                    navigate(`/detaile/${item._id}`)
                                }} key={index} hoverable style={{ width: "100%", margin: "5px 0" }}
                                    cover={<img alt="example" style={{ width: "100%", height: '150px' }} src={base_url + item.Cover_img} />}
                                >
                                    <div style={{}}>
                                        <p className={styles.overline_2}><span>{item.title}</span> <span>{item.review}浏览</span></p>
                                        <p className={styles.overline2}>{item.texttual}</p>
                                    </div>
                                </Card>
                            })
                            : ''
                    }
                </Drawer>
                {/* 移动端的抽屉用户 */}
                <Drawer
                    closable
                    placement="left"
                    destroyOnClose
                    rootClassName={styles.draw_left}
                    title={<p >个人中心</p>}
                    open={useinfo_show}
                    loading={loading}
                    onClose={() => setuser_info(false)}
                    style={{ width: '200px' }}
                >
                    <div style={{ width: '100%', display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
                        <p style={{ fontSize: '20px', textAlign: "center", margin: '5px 0' }}>用户</p>
                        <Avatar className="editUser" alt="加载错误" size={50} src={base_url + userinfo.avatar} style={{ margin: '5px 0' }}></Avatar>
                        <h1>{userinfo.username ? userinfo.username : ""}</h1>
                        <div style={{ margin: "10px" }} className={styles.overline_1}><span>收藏：{usercollect.collect}</span> <span>发布：{usercollect.foods}</span> </div>
                        <a href={userinfo.bilibili ? userinfo.bilibili : ''} target="_blank" style={{ display: 'flex', flexDirection: "column", justifyContent: "center", alignItems: "center" }}><BilibiliFilled style={{ fontSize: 30, color: "deeppink" }} /> <span>bilibili</span></a>

                    </div>

                </Drawer>
            </div>
        </animated.div >
    )
}

export default Home